package com.jh3502.vivo.utils.jpush;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Iterator;

import cn.jpush.android.api.JPushInterface;


/**
 * 自定义接收器
 * <p>
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class JpushReceiver extends BroadcastReceiver {
    public static final String PUSH_TYPE_CLUE_AD = "CLUE_AD";
    public static final String PUSH_TYPE_SAFETY_ADD = "SAFETY_ADD";
    public static final String PUSH_TYPE_SAFETY_NEW = "SAFETY_HAS_NEW";
    public static final String PUSH_TYPE_FRIEND_VERIFY = "FRIEND_VERIFY";
    public static final String PUSH_TYPE_MESSAGE = "MESSAGE";
    public static final String PUSH_SAFETY_FRIEND_NEW = "SAFETY_FRIEND_NEW";
    public static final String PUSH_POLICE_CALL_119 = "POLICE_CALL_119";
    public static final String PUSH_POLICE_CALL_110 = "POLICE_CALL_110";
    public static final String SEND_TASK = "SEND_TASK";
    public static final String SEND_TASK_CHECK = "SEND_TASK_CHECK";
    public static final String FIRE_CHECK_WARNING = "FIRE_CHECK_WARNING";
    public static final String FIRE_CHECK_FACILITIES_ID = "FIRE_CHECK_FACILITIES_ID";
    private static final String TAG = "JpushReceiver";
    private Gson mGson = new Gson();

    public static HashMap<String, Object> jso2map(String s) {
        JSONObject jsonObjTemp;
        HashMap<String, Object> map = new HashMap<String, Object>(3);
        try {
            jsonObjTemp = new JSONObject(s);
            Iterator ite = jsonObjTemp.keys();
            while (ite.hasNext()) {
                String key = ite.next().toString();
                String value = jsonObjTemp.get(key).toString();
                map.put(key, value);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return map;
    }

    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
                    Log.i(TAG, "This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next();
                        sb.append("\nkey:" + key + ", value: [" +
                                myKey + " - " + json.optString(myKey) + "]");
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            Bundle bundle = intent.getExtras();
            Log.i(TAG, "[JpushReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));

            if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
                String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
                Log.i(TAG, "[JpushReceiver] 接收Registration Id : " + regId);
            } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
                Log.i(TAG, "[JpushReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
            } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
                Log.i(TAG, "[JpushReceiver] 接收到推送下来的通知");
                int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
                Log.i(TAG, "[JpushReceiver] 接收到推送下来的通知的ID: " + notifactionId);
                String extra = bundle.getString(JPushInterface.EXTRA_EXTRA);
            } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
                Log.i(TAG, "[JpushReceiver] 用户点击打开了通知");
                String extra = bundle.getString(JPushInterface.EXTRA_EXTRA);
                Log.i(TAG, "---extra===" + extra);
                try {
                    JSONObject jsonObject = new JSONObject(extra);
                    extra = jsonObject.getString("message");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Log.i(TAG, "---extra===" + extra);
//				DeviceEvent deviceEvent = mGson.fromJson(extra, DeviceEvent.class);
//				Log.i(TAG, "---DeviceEvent===" + deviceEvent.toString());
//				switch (deviceEvent.getEvent()){
//					case PUSH_TYPE_CLUE_AD:
//						Log.i(TAG, "---PUSH_TYPE_CLUE_AD===" + deviceEvent.toString());
//						HashMap<String, Object> stringObjectHashMap = jso2map(deviceEvent.getBody().toString());
//						Intent intent1 = new Intent(context, ClueRewardActivity.class);
////						Log.i(TAG,(String) stringObjectHashMap.get("money")+"--"+(String) stringObjectHashMap.get("clueId"));
//						intent1.putExtra("money", (String) stringObjectHashMap.get("money"));
//						intent1.putExtra("id", (String) stringObjectHashMap.get("clueId"));
//						intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//						context.startActivity(intent1);
//						break;
//					case PUSH_TYPE_SAFETY_ADD:
//						Intent intent2 = new Intent(context, WatcherAgreeListActivity.class);
//						intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//						context.startActivity(intent2);
//						break;
//					case PUSH_TYPE_SAFETY_NEW:
//						HashMap<String, Object> hasNewSafety = jso2map(deviceEvent.getBody().toString());
//						Bundle safetyParams = new Bundle();
//						safetyParams.putString(SafetyRecordsDetailActivity.SECURITY_ID, (String) hasNewSafety.get("id"));
//						safetyParams.putString(SafetyRecordsDetailActivity.USER_ID, (String) hasNewSafety.get("userId"));
//						safetyParams.putString(SafetyRecordsDetailActivity.NAME, (String) hasNewSafety.get("name"));
//						safetyParams.putBoolean(SafetyRecordsDetailActivity.IS_USING, true);
//						Intent intent3 = new Intent(context, SafetyRecordsDetailActivity.class);
//						intent3.putExtras(safetyParams);
//						intent3.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//						context.startActivity(intent3);
//						break;
//					case PUSH_TYPE_FRIEND_VERIFY:
//						Intent intent4 = new Intent(context, WatcherListActivity.class);
//						intent4.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//						context.startActivity(intent4);
//						break;
//					case PUSH_TYPE_MESSAGE:
//						Intent messageIntent = new Intent(context, MessageDetailActivity.class);
//						messageIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//						messageIntent.putExtra(MessageDetailActivity.MESSAGE_ID, (String)deviceEvent.getBody());
//						context.startActivity(messageIntent);
//						break;
//					case PUSH_SAFETY_FRIEND_NEW:
//						Intent intent5 = new Intent(context, WatcherAgreeListActivity.class);
//						intent5.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//						context.startActivity(intent5);
//						break;
//					case PUSH_POLICE_CALL_119:
//						JsonElement jsonElement = mGson.toJsonTree(deviceEvent.getBody());
//						MediaSessionBean mediaSessionBean = mGson.fromJson(jsonElement, MediaSessionBean.class);
//						if (mediaSessionBean == null){
//							break;
//						}
//						if (mediaSessionBean.getPublishers() == null){
//							mediaSessionBean.setPublishers(6);
//						}
//						Intent intent6 = new Intent(context, WebRtcActivity.class);
//						intent6.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//						intent6.putExtra(Constant.VIDEO_CASE_INFO, mediaSessionBean);
//						intent6.putExtra(Constant.CALL_TYPE, Constant.CALL_119);
//						intent6.putExtra(Constant.CALL_VIDEO_DISPLAY_TYPE, false);
//						intent6.putExtra(Constant.IS_TEST_CALL, false);
//						intent6.putExtra(Constant.IS_C2C_CALL, true);
//						context.startActivity(intent6);
//						break;
//					case PUSH_POLICE_CALL_110:
//						JsonElement jsonElement1 = mGson.toJsonTree(deviceEvent.getBody());
//						MediaSessionBean mediaSessionBean2 = mGson.fromJson(jsonElement1, MediaSessionBean.class);Log.i(TAG, "---PUSH_POLICE_CALL_110===" + mediaSessionBean2.toString());
//						if (mediaSessionBean2.getPublishers() == null){
//							mediaSessionBean2.setPublishers(6);
//						}
//						Intent intent7 = new Intent(context, WebRtcActivity.class);
//						intent7.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//						intent7.putExtra(Constant.VIDEO_CASE_INFO, mediaSessionBean2);
//						intent7.putExtra(Constant.CALL_TYPE, Constant.CALL_110);
//						intent7.putExtra(Constant.CALL_VIDEO_DISPLAY_TYPE, false);
//						intent7.putExtra(Constant.IS_TEST_CALL, false);
//						intent7.putExtra(Constant.IS_C2C_CALL, true);
//						context.startActivity(intent7);
//						Log.i(TAG, "---PUSH_POLICE_CALL_110===");
//						break;
//					case SEND_TASK:
//						Intent intent8 = new Intent(context, CompanyPersonListActivity.class);
//						intent8.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//						context.startActivity(intent8);
//						break;
//					case SEND_TASK_CHECK:
//						Intent intent9 = new Intent(context, InspectionTasksDetailActivity.class);
//						intent9.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//						intent9.putExtra(TASK_ID,deviceEvent.getBody().toString());
//						context.startActivity(intent9);
//						break;
//					case FIRE_CHECK_WARNING:
//						Intent intent10 = new Intent(context, FireInspectionFileAddActivity.class);
//						intent10.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//						intent10.putExtra(FIRE_CHECK_FACILITIES_ID, (String) jso2map(deviceEvent.getBody().toString()).get("equipmentId"));
//						context.startActivity(intent10);
//						break;
//					default:
//				}

            } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
                Log.i(TAG, "[JpushReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
                //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..

            } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
                boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
                Log.i(TAG, "[JpushReceiver]" + intent.getAction() + " connected state change to " + connected);
            } else {
                Log.i(TAG, "[JpushReceiver] Unhandled intent - " + intent.getAction());
            }
        } catch (Exception e) {

        }

    }


}
